package net.kazed.nextaction;

import net.kazed.android.inject.ApplicationContext;
import net.kazed.nextaction.database.ContextCache;
import net.kazed.nextaction.database.GtdContext;
import net.kazed.nextaction.database.Task;
import net.kazed.nextaction.task.TaskAttachmentManager;
import net.kazed.nextaction.task.TaskAttachmentManagerImpl;
import android.app.Application;
import android.content.Context;
import android.database.ContentObserver;
import android.os.Handler;

/**
 * Application class for NextAction.
 * @author Koert Zeilstra
 */
public class NextActionApplication extends Application {

   public static final String PACKAGE = NextActionApplication.class.getPackage().getName();

   private ContextCache contextCache;
   private ApplicationResource applicationResource;
   private ApplicationContext applicationContext;

   /**
    * @return Cache for contexts.
    */
   public ContextCache getContextCache() {
      if (contextCache == null) {
         contextCache = new ContextCache(getContentResolver());
         Handler handler = new Handler();
         getContentResolver().registerContentObserver(GtdContext.CONTENT_URI, true, new ContentObserver(handler) {
            @Override
            public boolean deliverSelfNotifications() {
               return true;
            }
            @Override
            public void onChange(boolean selfChange) {
               super.onChange(selfChange);
               contextCache.clearCache();
            }
            
         });
         getContentResolver().registerContentObserver(Task.CONTENT_URI, true, new ContentObserver(handler) {
            @Override
            public boolean deliverSelfNotifications() {
               return true;
            }
            @Override
            public void onChange(boolean selfChange) {
               super.onChange(selfChange);
               contextCache.clearCache();
            }
            
         });
      }
      return contextCache;
   }

   /**
    * @param contextCache Cache for contexts.
    */
   public void setContextCache(ContextCache contextCache) {
      this.contextCache = contextCache;
   }
   
   /**
    * @return Application resources.
    */
   public ApplicationResource getApplicationResource() {
       if (applicationResource == null) {
           applicationResource = new ApplicationResource();
       }
       return applicationResource;
   }

   /**
    * @return Application context.
    */
   public synchronized ApplicationContext getAppContext() {
       if (applicationContext == null) {
           applicationContext = new ApplicationContext();
           applicationContext.bind(TaskAttachmentManager.class, TaskAttachmentManagerImpl.class);
           applicationContext.bindInstance(Context.class, getApplicationContext());
       }
       
       return applicationContext;
   }
   
}
